import React, { useContext } from 'react';
import { useRequest } from 'ahooks';
import { Row, Typography } from 'antd';
import PieChart from '@/components/MarketingMap/PieChart';
import DateFrom from '@/components/MarketingMap/DateFrom';
import CustomCard from '@/components/MarketingMap/CustomCard';
import { formatValue, sortByKey, isCategory } from '@/utils/marketingMap/utils';
import styles from '../styles/panel.less';
import { fetchUserProfile } from '@/services/marketingMap/overallAnalysis';
import OverallContext from '../context';
import TabelLoadMore from '@/components/MarketingMap/TabelLoadMore';
import TipMessage from '@/components/MarketingMap/TipMessage';
import BarChart from '@/components/MarketingMap/BarChart';
import BarEchart from '@/components/MarketingMap/BarEchart';
// import { colors } from '@/utils/marketingMap/utils';

// const content = (data: {
//   name: string;
//   ourCount: number;
//   otherCount: number;
//   bothCount: number;
//   noneCount: number;
// }) => `
//   <div class="title">${data.name}</div>
//   <div class="item"><span style="padding: 2px; background: ${colors[0]}; margin-right: 10px; border-radius: 50%;"></span> 仅回本店售后<span class="text">${formatValue(data.ourCount)}</span>台</div>
//   <div class="item"><span style="padding: 2px; background: ${colors[1]}; margin-right: 10px; border-radius: 50%;"></span>回本店和其他售后店<span class="text">${formatValue(
//     data.bothCount,
//   )}</span>台</div>
//   <div class="item"><span style="padding: 2px; background: ${colors[2]}; margin-right: 10px; border-radius: 50%;"></span>仅在其他店售后<span class="text">${formatValue(data.otherCount)}</span>台</div>
//   <div class="item"><span style="padding: 2px; background: ${colors[3]}; margin-right: 10px; border-radius: 50%;"></span>未回厂售后<span class="text">${formatValue(data.noneCount)}</span>台</div>
// `;

const content = (data: {
  name: string;
  vehicleCount: number;
  percent: number;
}) => `
  <div class="title">${data.name}</div>
  <div class="item">售后车辆数<span class="text">${formatValue(data.vehicleCount)}</span>台</div>
  <div class="item">占比<span class="text">${formatValue(data.percent)}</span>%</div>
`;


const UserProfile = ({ map, markerClick }) => {
  const { query, date, onSubmit } = useContext(OverallContext);
  const { data, loading } = useRequest(() => fetchUserProfile(query), {
    refreshDeps: [query],
  });

  const columns = [
    {
      title: '排名',
      dataIndex: 'rank',
      key: 'rank',
    },
    {
      title: <TipMessage name="售后分析-常驻地">常驻地</TipMessage>,
      dataIndex: 'name',
      key: 'name',
      render: (text: string, _) => (
        <Typography.Text style={{ width: 300 }} ellipsis={{ tooltip: text }}>
          <Typography.Link
            onClick={() => {
              if(!_.geoLon || ! _.geoLat) return
              map.setCenter([_.geoLon, _.geoLat], true);
              markerClick(content(_), [_.geoLon, _.geoLat]);
            }}
          >
            {text}
          </Typography.Link>
        </Typography.Text>
      ),
    },
    {
      title: <TipMessage name="售后分析-售后车辆数">售后车辆数</TipMessage>,
      dataIndex: 'vehicleCount',
      key: 'vehicleCount',
    },
    {
      title: '占比',
      dataIndex: 'percent',
      key: 'percent',
      render: (text: number) => formatValue(text, '%'),
      // render: (text: number) => formatValue(Math.round((text * 100 + Number.EPSILON) * 100) / 100, '%'),
    },
  ];

  return (
    <div className={styles.sidenar_wrapper}>
      <DateFrom value={date} onChange={onSubmit} />
      <div>
        <Row justify="space-between" className={styles.title}>
          <Typography.Text strong>售后车辆常驻地排名</Typography.Text>
          <Typography style={{ color: '#0009', textAlign: 'right', paddingRight: 24 }}>
            总售后车辆数：{formatValue(data?.[0]?.totalVehicleCount)}
          </Typography>
        </Row>
        <TabelLoadMore
          columns={columns}
          dataSource={data?.[0]?.residencyData}
          rowKey="name"
          loading={loading}
        />
      </div>
      <div>
        <Typography className={styles.title}>
          <Typography.Text strong>保客人群分布</Typography.Text>
        </Typography>
        <CustomCard
          loading={loading}
          empty={!data?.[1]?.length}
          title={<Typography.Text strong>车系分布</Typography.Text>}
          extra={<Typography.Text style={{ fontSize: 12 }}>售后（次）</Typography.Text>}
        >
          <PieChart
            name="车系分布"
            title="全部售后"
            data={sortByKey(data?.[1], 'count')?.map(
              (item: { count: number; percent: string; name: string }) => ({
                value: item.count,
                percent: item.percent + '%',
                name: item.name,
              }),
            )}
          />
        </CustomCard>
        <CustomCard
          loading={loading}
          empty={!data?.[2]?.length}
          style={{ marginTop: 12 }}
          title={<Typography.Text strong>售后项目分布</Typography.Text>}
          extra={<Typography.Text style={{ fontSize: 12 }}>售后（次）</Typography.Text>}
        >
          <PieChart
            name="售后项目分布"
            title="全部售后"
            data={data?.[2]?.map((item: { count: number; percent: string; name: string }) => ({
              value: item.count,
              percent: item.percent + '%',
              name: item.name,
            }))}
            // data={mapper.map((key, index) => ({
            //   name: key,
            //   value:
            //     data?.[2]?.find((item: { type: number }) => item.type === index)
            //       ?.count || 0,
            //   percent:
            //     (data?.[2]?.find((item: { type: number }) => item.type === index)
            //       ?.percent || 0) + '%',
            // }))}
          />
        </CustomCard>
        <CustomCard
          loading={loading}
          empty={!data?.[3]?.length}
          style={{ marginTop: 12 }}
          title={
            <TipMessage name="售后用户类型分布">
              <Typography.Text strong>售后用户类型分布</Typography.Text>
            </TipMessage>
          }
        >
          <BarChart
            title="用户类型分布"
            name="用户数（个）"
            data={data?.[3]?.map((item: { name: any; count: any }) => ({
              name: item.name,
              data: [item?.count || 0],
            }))}
          />
        </CustomCard>
        <CustomCard
          loading={loading}
          empty={!data?.[4]?.length}
          style={{ marginTop: 12 }}
          title={
            <Row align="bottom" style={{ gap: 6 }}>
              <Typography.Text strong>售后用户年龄分布</Typography.Text>
              {isCategory(data?.[4]) && (
                <span style={{ fontSize: 12 }}>(无法判断性别年龄 {data[4][0].vins}人)</span>
              )}
            </Row>
          }
        >
          <BarEchart title="用户年龄分布" name="用户数（个）" data={data?.[4]} />
        </CustomCard>
      </div>
    </div>
  );
};

export default UserProfile;
